package com.study.concurrency;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreExample {

	public static Semaphore semaphore = new Semaphore(3);
	
	public static void main(String[] args) {
		
		ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();  //newCachedThreadPool是类方法
		
		for(int i = 0; i < 10; i++){
			newCachedThreadPool.execute(new MyTask(i));
		}
	}
	
	static class MyTask implements Runnable{

		private int num;
		
		public MyTask(int num){
			this.num = num;
		}
		
		//最多同时有三个线程并发执行，也可以认为有三个公共资源
		@Override
		public void run() {
			try {
				semaphore.acquire();
				System.out.println("Mytask is running." + num);
				Thread.sleep(new Random().nextInt(2000));
				semaphore.release();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
		}
		
	}
	
}

